package org.nicocube.airain.gwt.server;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;

import org.nicocube.airain.domain.client.character.Action;
import org.nicocube.airain.domain.client.data.StorageException;
import org.nicocube.airain.domain.server.criteria.ConstraintCriteria;
import org.nicocube.airain.domain.server.data.OrderedStorage;
import org.nicocube.airain.gwt.client.rpc.ActionService;

import com.allen_sauer.gwt.log.client.Log;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class ActionServiceImpl extends RemoteServiceServlet implements ActionService {
	// as for version 0.1
	private static final long serialVersionUID = 1L;

	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		
	}

	public Set<Action> retrieveAction(Long gcOrder) {
		try {
			OrderedStorage<Action> as = getActionStorage();
			Set<Action> result = new HashSet<Action>(as.retrieve(new ConstraintCriteria<Long>("gameCharacterOrder",gcOrder)));
			return result;
		} catch (Exception e) {
			Log.error("Error while retrieving actions for GameCharacter("+gcOrder+")",e);
			throw new IllegalStateException("Error while retrieving actions for GameCharacter("+gcOrder+")",e);
		}
	}	

	public Set<Action> saveAction(Set<Action> actions) {
		try {
			OrderedStorage<Action> as = getActionStorage();
			for (Action action : actions) {
				as.save(action);
			}
			as.commit();
			if (Log.isDebugEnabled()) Log.debug("server-side:"+Arrays.deepToString(actions.toArray()));
			return actions;
		} catch (Exception e) {
			Log.error("Error while saving actions",e);
			throw new IllegalStateException("Error while saving actions",e);
		}
	}

	private OrderedStorage<Action> getActionStorage() throws StorageException {
		return StorageManager.getStorageProvider().getStorage(Action.class);
	}

}
